package com.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bean.pojo.ItripUser;
import com.service.TokenService;
import com.util.MD5;
import com.util.RedisUtil;
import com.util.UserAgentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisUtil redisUtil;

    private String prefix = "token:";
    private int expire = 7200;

    @Override
    public String generate(ItripUser user, String agent) {

        StringBuilder token = new StringBuilder(prefix);

        //设备信息
        boolean isMobile = UserAgentUtil.CheckAgent(agent);
        if (isMobile){
            token.append("moblie");
        }else {
            token.append("pc");
        }

        //用户账户
        token.append("-" + user.getUserCode());

        //用户ID
        token.append("-" + user.getId());

        //用户名(加密)
        token.append("-" + MD5.getMd5(user.getUserName(), 32));

        //登录时间, yyyyMMddHHmmssSSS 或 总毫秒数
        token.append("-" + new Date().getTime());

        //随机6位数 或 根据设备信息获取的6位加密字符串
        token.append("-" + MD5.getMd5(agent, 6));

        return token.toString();
    }

    @Override
    public void save(String token, ItripUser user, String agent) {
        System.out.println("是否移动设备"+UserAgentUtil.CheckAgent(agent));
        /** 根据登录设备的不同, 设置不同的有效时长 */
        if (UserAgentUtil.CheckAgent(agent)){
            redisUtil.setString(token, JSONObject.toJSONString(user));
        } else {
            redisUtil.setString(token, JSONObject.toJSONString(user), expire);
        }


    }

    @Override
    public ItripUser read(String token) {

        //判断, token是否有效
        if (!redisUtil.exists(token)) return null;

        //有效
        return JSONObject.parseObject(redisUtil.getString(token), ItripUser.class);
    }

    @Override
    public String replace(String token, String agent) {

        //判断, 旧token是否有效
        if (!redisUtil.exists(token)) return null;

        //获取登录信息
        ItripUser loginInfo = JSONObject.parseObject(redisUtil.getString(token), ItripUser.class);

        //将旧token的有效时间设置为60
        redisUtil.setString(token, "", 60);

        //生成新token
        String newToken = generate(loginInfo, agent);

        //保存
        save(newToken, loginInfo, agent);

        return newToken;
    }
}
